﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;

namespace Cellz.App
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();            
            var sheet = new Sheet(26, 30);
            for (int n = 0; n < sheet.ColumnCount; n++) 
                Sheet.Columns.Add(GetColumn(sheet, n));
            Sheet.LoadingRow += (_, args) =>
            {
                var row = args.Row.DataContext as Row;
                args.Row.Header = row.Index;
            };
            Sheet.ItemsSource = sheet.Rows;
        }

        private DataGridColumn GetColumn(Sheet sheet, int n)
        {            
            var header = colIndex.toColName(n);
            var col = new DataGridTemplateColumn { Header = header, IsReadOnly = false };
            col.Width = new DataGridLength(sheet.Columns[n].Width);
            var path = string.Format("Cells.[{0}]", n);
            var cellTemplate =
                string.Format(
                    "<Grid Background='{{Binding {0}.Background}}'>" +
                     "<Border Style='{{Binding {0}.BorderStyle}}'>" +
                     "<TextBlock Style='{{Binding {0}.FontStyle}}'" +
                               " Text='{{Binding {0}.Value}}'" +
                               " TextTrimming='WordEllipsis'" +
                               " ToolTipService.ToolTip='{{Binding {0}.Formula}}'/>" +
                     "</Border>" +
                    "</Grid>", path);
            col.CellTemplate = ToDataTemplate(cellTemplate);
            var cellEditingTemplate =
                string.Format("<TextBox Text='{{Binding {0}.Data,Mode=TwoWay}}'/>", path);
            col.CellEditingTemplate = ToDataTemplate(cellEditingTemplate);
            return col;
        }

        private DataTemplate ToDataTemplate(string s)
        {
            var ns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
            var xaml = string.Format(@"<DataTemplate xmlns='{0}'>{1}</DataTemplate>", ns, s);
            return (DataTemplate) XamlReader.Load(xaml);
        }
    }
}
